﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigurationDemo
{
    //基于内存的配置提供程序扩展方法
    public static class MemoryConfigurationBuilderExtensions
    {
        public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder)
        {
            configurationBuilder.Add(new MemoryConfigurationSource());
            return configurationBuilder;
        }
        public static IConfigurationBuilder AddInMemoryCollection(
            this IConfigurationBuilder configurationBuilder,
            IEnumerable<KeyValuePair<string, string?>>? initialData)
        {
            configurationBuilder.Add(new MemoryConfigurationSource { InitialData = initialData });
            return configurationBuilder;
        }
    }
    //基于内存的配置源
    public class MemoryConfigurationSource : IConfigurationSource
    {
        public IEnumerable<KeyValuePair<string, string?>>? InitialData { get; set; }

        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            return new MemoryConfigurationProvider(this);
        }
    }

    //基于内存的配置提供程序
    public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerable<KeyValuePair<string, string?>>
    {
        private readonly MemoryConfigurationSource _source;

        public MemoryConfigurationProvider(MemoryConfigurationSource source)
        {
            _source = source;
            //将配置源中的初始数据添加到内存配置提供程序中
            if (_source.InitialData != null)
            {
                foreach (KeyValuePair<string, string?> pair in _source.InitialData)
                {
                    Data.Add(pair.Key, pair.Value);
                }
            }
        }

        public void Add(string key, string? value)
        {
            Data.Add(key, value);
        }
        public IEnumerator<KeyValuePair<string, string?>> GetEnumerator()
        {
            return Data.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
